#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from .HTMLTestRunner import HTMLTestRunner
import unittest
import time
import os
from pyse.mail.new_report import NewReport
from pyse.mail.send_mail import SendMail


class TestRunner(object):

    def __init__(self, cases='./'):
        self.cases = cases
        self.current_file_dir = os.path.dirname(self.cases)

    def run(self, title_text='测试报告', description_text='Env: win10'):
        # 在当前目录下创建测试报告report目录
        for filename in os.listdir(self.current_file_dir):
            if filename == 'report':
                break
        else:
            os.mkdir(self.current_file_dir + '/report')
            os.mkdir(self.current_file_dir + '/report/image')

        # 测试报告的绝对路径
        report_abspath = os.path.abspath(self.current_file_dir + '/report').replace("\\", "/")
        # 把报告路径写入report.txt文件
        base_dir = os.path.dirname(os.path.dirname(__file__))
        f = open(base_dir + '/reporting/report.txt', 'w')
        f.write(report_abspath)
        f.close()

        now = time.strftime("%Y-%m-%d_%H_%M_%S")
        filename = os.path.dirname(self.cases)+'/report/'+now+'result.html'
        fp = open(filename, 'wb')
        discover = unittest.defaultTestLoader.discover(self.cases, pattern='*_case.py', top_level_dir=None)
        runner = HTMLTestRunner(stream=fp, title=title_text, description=description_text)
        runner.run(discover)
        fp.close()
        print('=> 生成测试报告成功')

    def send_mail(self):
        """
        find the latest report and send mail to the receiver.
        """
        new_report = NewReport().new_report()
        SendMail().send_mail(new_report)


if __name__ == '__main__':
    test = TestRunner()
    test.run()
